package com.example.module_android_demo;
 
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
 
import android.app.Activity;
import android.app.Application;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;

import com.function.AndroidWakeLock;
import com.function.SPconfig;
import com.handheld.uhfdemo3.R;
import com.pow.api.cls.RfidPower;
import com.pow.api.cls.RfidPower.PDATYPE;
import com.uhf.api.cls.Reader;
import com.uhf.api.cls.Reader.AntPower;
import com.uhf.api.cls.Reader.AntPowerConf;
import com.uhf.api.cls.Reader.EmbededData_ST;
import com.uhf.api.cls.Reader.HardwareDetails;
import com.uhf.api.cls.Reader.HoptableData_ST;
import com.uhf.api.cls.Reader.Inv_Potl;
import com.uhf.api.cls.Reader.Inv_Potls_ST;
import com.uhf.api.cls.Reader.Mtr_Param;
import com.uhf.api.cls.Reader.READER_ERR;
import com.uhf.api.cls.Reader.Region_Conf;
import com.uhf.api.cls.Reader.SL_TagProtocol;
import com.uhf.api.cls.Reader.TAGINFO;
import com.uhf.api.cls.Reader.TagFilter_ST;

@SuppressWarnings("deprecation")
public class MainActivityTwo extends TabActivity  {

	// 读线程：
	boolean isrun;
	private Thread runThread;
	
	ExpandableListView tab4_left,tab4_right;
	TextView tv_once,tv_state,tv_tags,tv_costt;
	Button button_read,button_stop,button_clear;
	private ListView listView;
	
	Map<String,TAGINFO> TagsMap=new LinkedHashMap<String,TAGINFO>();//有序
	private Handler handler = new Handler( );
	private MyApplication myapp;
	private SoundPool soundPool;
	TabHost tabHost;
//	ScreenListener l;
	AndroidWakeLock Awl;
	int Test_count=0;
	boolean autostop;
	
	//RULE 默认平台
	boolean RULE_NOSELPT=false;
	PDATYPE PT=PDATYPE.ALPS_KT45Q;
	
	//for cz8800
	boolean D1,D2;
	
	 List<Byte> LB=new ArrayList();
	 List<Map<String, ?>> ListMs = new ArrayList<Map<String, ?>>();
     MyAdapter Adapter;
	 Map<String, String> h = new HashMap<String, String>();
	 long Starttime;
		
	public class MyEpListAdapter extends ArrayAdapter<Object>
	{

		@SuppressWarnings("unchecked")
		public MyEpListAdapter(Context context, int resource,
				int textViewResourceId, @SuppressWarnings("rawtypes") List objects) {
			super(context, resource, textViewResourceId, objects);
			// TODO Auto-generated constructor stub
		}
		
	}
	 
	public Handler handler2 = new Handler()  
    {  
        @Override  
        public void handleMessage(Message msg)  
        {  
        	 Bundle bd=msg.getData();
            switch (msg.what)  
            {  
                case 0:  
                {  
                	 String count=bd.get("Msg_cnt").toString();
                	 tv_once.setText(count);
                	 tv_tags.setText(bd.get("Msg_all").toString());
     			     break;
		 			 
                }
                case 1:
                {	  button_read.setText("读");
					 tv_state.setText(bd.get("Msg_error_1").toString());
					// button_stop.performClick();
	 				 break;
                }
                case 2:
                {
                	 tv_state.setText(bd.get("Msg_error_2").toString());
                	 
	 				 break;
                }
                case 3:
                {
                	isrun=false;
					try {
						runThread.join();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					handler.removeCallbacks(runnable_refreshlist);
					StopHandleUI();
                	break;
                }
            }
        }
    };
    public static boolean runRootCommand(String command) {
    	Process process = null;
    	DataOutputStream os = null;
    	try {
			Process process2 = Runtime.getRuntime().exec("su");
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}  

    	try {
    	    process = Runtime.getRuntime().exec("sh");//Runtime.getRuntime().exec("su");
    	    os = new DataOutputStream(process.getOutputStream());
    	    os.writeBytes(command + "\n");
    	    os.writeBytes("exit\n");
    	    os.flush();
    	    process.waitFor();
    	} catch (Exception e) {
    	    Log.d("Phone Link",  "su root - the device is not rooted,  error message： " + e.getMessage());
    	    return false;
    	} finally {
    	    try {
    	        if(null != os) {
    	            os.close();
    	    }
    	    if(null != process) {
    	        process.destroy();
    	    }
    	    } catch (Exception e) {
    	        e.printStackTrace();
    	    }
    	}
    	return true;
    	}


	MyEpListAdapter mttab1adp;
	
	private boolean reconnect()
	{
		Log.d("MYINFO", "reconenct");
		boolean blen=myapp.Rpower.PowerUp();
		if(!blen)
			return false;
		Toast.makeText(MainActivityTwo.this, "上电："+String.valueOf(blen),
				Toast.LENGTH_SHORT).show();
		
		READER_ERR er=myapp.Mreader.InitReader_Notype(myapp.Address, myapp.antportc);
		if(er==READER_ERR.MT_OK_ERR)
		{	
			 tv_state.setText("");
			myapp.needreconnect=false;
			try
			{

				myapp.Rparams=myapp.spf.ReadReaderParams();
				
				 if(myapp.Rparams.invpro.size()<1)
					 myapp.Rparams.invpro.add("GEN2");
			   
			    	 List<SL_TagProtocol> ltp=new ArrayList<SL_TagProtocol>();
					   for(int i=0;i<myapp.Rparams.invpro.size();i++)
					   {  if(myapp.Rparams.invpro.get(i).equals("GEN2"))
					    	{ ltp.add(SL_TagProtocol.SL_TAG_PROTOCOL_GEN2);
					    	 
					    	}
					   else if(myapp.Rparams.invpro.get(i).equals("6B"))
					    	{
					    	  ltp.add(SL_TagProtocol.SL_TAG_PROTOCOL_ISO180006B);
					    	 
					    	}
					   else if(myapp.Rparams.invpro.get(i).equals("IPX64"))
					    	{
					    	   ltp.add(SL_TagProtocol.SL_TAG_PROTOCOL_IPX64);
					    	   
					    	}
					   else if(myapp.Rparams.invpro.get(i).equals("IPX256"))
					    	{
					    	  ltp.add(SL_TagProtocol.SL_TAG_PROTOCOL_IPX256);
					    	  
					    	}
					   }
					     
						Inv_Potls_ST ipst=myapp.Mreader.new Inv_Potls_ST();
						ipst.potlcnt=ltp.size();
						ipst.potls=new Inv_Potl[ipst.potlcnt];
						SL_TagProtocol[] stp=ltp.toArray(new SL_TagProtocol[ipst.potlcnt]);
						for(int i=0;i<ipst.potlcnt;i++)
						{
							Inv_Potl ipl=myapp.Mreader.new Inv_Potl();
							ipl.weight=30;
							ipl.potl=stp[i];
							ipst.potls[0]=ipl;
						}
						
					  er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_TAG_INVPOTL, ipst);
				      Log.d("MYINFO", "Connected set pro:"+er.toString());
		 
				 er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_READER_IS_CHK_ANT,
						 new int[]{myapp.Rparams.checkant});
				 Log.d("MYINFO", "Connected set checkant:"+er.toString());
				 
					
				 AntPowerConf apcf=myapp.Mreader.new AntPowerConf();
					apcf.antcnt=myapp.antportc;
					for(int i=0;i<apcf.antcnt;i++)
					{
						AntPower jaap=myapp.Mreader.new AntPower();
						jaap.antid=i+1;
						jaap.readPower =(short)myapp.Rparams.rpow[i];
						jaap.writePower=(short)myapp.Rparams.wpow[i];
						apcf.Powers[i]=jaap; 
					}
					
				myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_RF_ANTPOWER, apcf);
				 
				Region_Conf rre;
				 switch(myapp.Rparams.region)
				 {
				 case 0:
					 rre =Region_Conf.RG_PRC;
					 break;
				 case 1:
					 rre = Region_Conf.RG_NA;
					 break;
				 case 2:
					 rre=Region_Conf.RG_NONE;
					 break;
				 case 3:
					 rre=Region_Conf.RG_KR;
					 break;
				 case 4:
					 rre=Region_Conf.RG_EU;
					 break;
				 case 5:
				 case 6:
				 case 7:
				 case 8:
				 default:
					 rre=Region_Conf.RG_NONE;
					 break;
				 }
				 if(rre!=Region_Conf.RG_NONE)
				 {
					 er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_FREQUENCY_REGION,rre);
				 }
	  
				if(myapp.Rparams.frelen>0)
				{
					 
						HoptableData_ST hdst=myapp.Mreader.new HoptableData_ST();
						hdst.lenhtb=myapp.Rparams.frelen;
						hdst.htb=myapp.Rparams.frecys;
						  er=myapp.Mreader.ParamSet
								(Mtr_Param.MTR_PARAM_FREQUENCY_HOPTABLE,hdst);
				}
				 
				er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_POTL_GEN2_SESSION,
								new int[]{myapp.Rparams.session});
				er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_POTL_GEN2_Q,
						new int[]{myapp.Rparams.qv});
				er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_POTL_GEN2_WRITEMODE,
						new int[]{myapp.Rparams.wmode});
				er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_POTL_GEN2_MAXEPCLEN,
						new int[]{myapp.Rparams.maxlen});
				er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_POTL_GEN2_TARGET,
						new int[]{myapp.Rparams.target});
				 
				if(myapp.Rparams.filenable==1)
				{
					 TagFilter_ST tfst=myapp.Mreader.new TagFilter_ST();
					 tfst.bank=myapp.Rparams.filbank;
					 tfst.fdata=new byte[myapp.Rparams.fildata.length()/2];
					 myapp.Mreader.Str2Hex(myapp.Rparams.fildata,
							 myapp.Rparams.fildata.length(), tfst.fdata);
					 tfst.flen=tfst.fdata.length*8;
					 tfst.startaddr=myapp.Rparams.filadr;
					 tfst.isInvert=myapp.Rparams.filisinver;
			       
					 myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_TAG_FILTER, tfst);
				}
			 
				if(myapp.Rparams.emdenable==1)
				{
					EmbededData_ST edst = myapp.Mreader.new EmbededData_ST();
					 
					edst.accesspwd=null;
					edst.bank=myapp.Rparams.emdbank;
					edst.startaddr=myapp.Rparams.emdadr;
					edst.bytecnt=myapp.Rparams.emdbytec;
					edst.accesspwd=null;
				 
					er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_TAG_EMBEDEDDATA,
							edst);
				}
				 
				er=myapp.Mreader.ParamSet
						(Mtr_Param.MTR_PARAM_TAGDATA_UNIQUEBYEMDDATA,
								new int[]{myapp.Rparams.adataq});
				er=myapp.Mreader.ParamSet
						(Mtr_Param.MTR_PARAM_TAGDATA_RECORDHIGHESTRSSI, 
								new int[]{myapp.Rparams.rhssi});
				er=myapp.Mreader.ParamSet
						(Mtr_Param.MTR_PARAM_TAG_SEARCH_MODE, 
								new int[]{myapp.Rparams.invw});

			} catch (Exception ex) {
				Log.d("MYINFO",
						ex.getMessage() + ex.toString() + ex.getStackTrace());
			}
		}
		else
			return false;
		
		return true;
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
//		unregisterReceiver(keyReceiver);
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_two);
		 String apkRoot="chmod 777 "+getPackageCodePath();
	     
	     runRootCommand(apkRoot);
 
		soundPool= new SoundPool(10,AudioManager.STREAM_SYSTEM,5);
		soundPool.load(this,R.raw.beep51,1);

		tabHost = (TabHost) findViewById(android.R.id.tabhost); 
		tabHost.setup();      
		 
		if(RULE_NOSELPT)
			;
		else
		 tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("连接",  
		getResources().getDrawable(R.drawable.ic_launcher)).setContent(
				new Intent(this, Sub1TabActivity.class)));
		
		 TabSpec tp=tabHost.newTabSpec("tab2").setIndicator("盘点") 
			.setContent(R.id.tab2);
		 
		tabHost.addTab(tp); 
		tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("读写锁",
				getResources().getDrawable(android.R.drawable.arrow_down_float)).setContent(
						new Intent(this, Sub3TabActivity.class)));
		 
		tabHost.addTab(tabHost.newTabSpec("tab4").setIndicator(
				"设置",
				getResources().getDrawable(android.R.drawable.arrow_down_float)).setContent(
				new Intent(this, Sub4TabActivity.class)));

		 TabWidget tw=tabHost.getTabWidget();
		 if(RULE_NOSELPT)
				;
		 else
		 {
		 tw.getChildAt(1).setVisibility(View.INVISIBLE);
		 tw.getChildAt(2).setVisibility(View.INVISIBLE);
		 tw.getChildAt(3).setVisibility(View.INVISIBLE);
		 }

		Application app=getApplication();
		myapp=(MyApplication)app;
		myapp.Mreader=new Reader();
		myapp.Rparams=myapp.new ReaderParams();
		myapp.tabHost=tabHost;
		button_read=(Button)findViewById(R.id.button_start);
		button_stop=(Button)findViewById(R.id.button_stop);
		button_stop.setEnabled(false);
		button_clear=(Button)findViewById(R.id.button_readclear);
		listView = (ListView) findViewById(R.id.listView_epclist); 
		
		tv_once=(TextView)findViewById(R.id.textView_readoncecnt);
		tv_state=(TextView)findViewById(R.id.textView_invstate);
	    tv_tags=(TextView)findViewById(R.id.textView_readallcnt);
	    tv_costt=(TextView)findViewById(R.id.textView_costtime);
	    for (int i = 0; i < Coname.length; i++)
			h.put(Coname[i], Coname[i]);
	    myapp.needreconnect=false;
//	    l = new ScreenListener(this);
	    
	    if(RULE_NOSELPT)
	    {
	    	 myapp.spf=new SPconfig(this);
	 	    myapp.Rpower=new RfidPower(PT);
	 	    String path=myapp.Rpower.GetDevPath();
	 	    if(myapp.Rpower.PowerUp())
	 	    {
	 	    	READER_ERR er=myapp.Mreader.InitReader_Notype(path, 1);
	 	    	myapp.antportc=1;
	 	    	myapp.Address=path;
	 	    	if(er==READER_ERR.MT_OK_ERR)
	 			{	
	 				ConnectHandleUI();
	 			}
	 	    }
	    }
	    
//	    l.begin(new ScreenStateListener() {
// 
//	    @Override
//	    public void onScreenOn() {
//			 
//	    }
//
//	    @Override
//	    public void onScreenOff() {
//	    	 
//	    	Log.d("MYINFO", "onScreenoff");
//	    	if(button_stop.isEnabled())
//	    	{   button_stop.performClick();}
//	    	  
//	    	if(myapp.Mreader!=null)
//				myapp.Mreader.CloseReader();
//				
//	    	if(myapp.Rpower!=null)
//	    	{	
//	    		
//	    		boolean blen=myapp.Rpower.PowerDown();
//				myapp.needreconnect=true;
//	    	}
//	    }
//	    });
	    
	    Awl=new AndroidWakeLock((PowerManager) getSystemService(Context.POWER_SERVICE));
	    
		button_read.setOnClickListener(new OnClickListener()
		{

			@SuppressWarnings("unused")
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				start_read();
			}

			private Activity getContext() {
				// TODO Auto-generated method stub
				return null;
			}
			
		});
		
		button_stop.setOnClickListener(new OnClickListener()
		{

			@SuppressWarnings("unused")
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub

				stop_read();

			}

		});
		
		button_clear.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				 if(Adapter!=null)
		           {
		        	   TagsMap.clear();
						myapp.TagsMap.clear();
						ListMs.clear();
					       // showlist();
						 
				         ListMs.add(h);
		        	   Adapter.notifyDataSetChanged();
		           }
		 
				    TextView et=(TextView)findViewById(R.id.textView_readoncecnt);
	 				et.setText("0");

	 				TextView et2=(TextView)findViewById(R.id.textView_readallcnt);
	 				et2.setText("0");
	 				
	 				TextView et3=(TextView)findViewById(R.id.textView_invstate);
	 				et3.setText("...");
	 				
	 				myapp.Curepc="";
			}
		});
		
		this.listView.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				arg1.setBackgroundColor(Color.YELLOW);
				
				@SuppressWarnings("unchecked")
				HashMap<String,String> hm=(HashMap<String,String>)listView.getItemAtPosition(arg2);
				String epc=hm.get("EPC ID");
				myapp.Curepc=epc;
				 
				for(int i=0;i<listView.getCount();i++)
				{
					if(i!=arg2)
					{	
						View v=listView.getChildAt(i);
						if(v!=null)
						{ColorDrawable cd=(ColorDrawable) v.getBackground();
						if(Color.YELLOW==cd.getColor())
						{
							int[] colors = {Color.WHITE, Color.rgb(219, 238, 244) };//RGB颜色 
							 v.setBackgroundColor(colors[i % 2]);// 每隔item之间颜色不同 
						}
						}
					}
				}
			}
			
		});
		
		tabHost.setOnTabChangedListener(new OnTabChangeListener(){

			@Override
			public void onTabChanged(String arg0) {
				int j=tabHost.getCurrentTab();
				if(RULE_NOSELPT)
				{
					if(j==1)
					{
						Sub3TabActivity.EditText_sub3fildata.setText(myapp.Curepc);
						Sub3TabActivity.EditText_sub3wdata.setText(myapp.Curepc);
					}
				}
				else{
				if(j==2)
				{
					Sub3TabActivity.EditText_sub3fildata.setText(myapp.Curepc);
					Sub3TabActivity.EditText_sub3wdata.setText(myapp.Curepc);
				}
				}
			}
		});
		keyReceiver = new KeyReceiver();
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("android.rfid.FUN_KEY");
		registerReceiver(keyReceiver,intentFilter);

	}
	private KeyReceiver keyReceiver;
	private void start_read(){
		try{
			if(Adapter==null)
			{ 
		         ListMs.add(h);
				Adapter  = new MyAdapter(getApplicationContext(),ListMs,
		 				R.layout.listitemview_inv, Coname,new int[] { R.id.textView_readsort,
		 				R.id.textView_readepc, R.id.textView_readcnt,R.id.textView_readant,
		 				R.id.textView_readpro,R.id.textView_readrssi,R.id.textView_readfre,
		 				R.id.textView_reademd});
		         
		     listView.setAdapter(Adapter);
			}
			
			boolean bl = true;
			if(myapp.needreconnect)
			{
				int c=0;
				do{
			  bl=reconnect();
			  if(!bl)
				  Toast.makeText(MainActivityTwo.this, "重连失败",
							Toast.LENGTH_SHORT).show();  
			     c++;
			     if(c>0)
			    	 break;
				}
				while(true);
			}
		    if(!bl)
		    	return;
		    
			if(myapp.nostop)
			{
			READER_ERR er=myapp.Mreader.AsyncStartReading(myapp.Rparams.uants,
					myapp.Rparams.uants.length, myapp.Rparams.option);
			if(er!=READER_ERR.MT_OK_ERR)
			{	 Toast.makeText(MainActivityTwo.this, "不停顿盘点启动失败",
							Toast.LENGTH_SHORT).show();
			     return;
			}
			}
			
			if(myapp.ThreadMODE==0)
			handler.postDelayed(runnable_MainActivity,0); 
			else
			{
				isrun=true;
				runThread=new Thread(runnable_alone);
				runThread.start();
				handler.postDelayed(runnable_refreshlist, 0);
			}
			Starttime=0;
			myapp.TagsMap.clear();
			ReadHandleUI();
			Awl.WakeLock();
		}catch(Exception ex)
		{
			Toast.makeText(MainActivityTwo.this, "开始盘点失败："+ex.getMessage(),
					Toast.LENGTH_SHORT).show();
		}
	}
	private void stop_read(){
		Awl.ReleaseWakeLock();
		if (myapp.nostop) {
			Log.d("MYINFO", "stop---");
			READER_ERR er = myapp.Mreader.AsyncStopReading();
			if (er != READER_ERR.MT_OK_ERR) {
				Toast.makeText(MainActivityTwo.this, "不停顿盘点停止失败",
						Toast.LENGTH_SHORT).show();
				return;
			}
		}

		if (myapp.ThreadMODE == 0)
			handler.removeCallbacks(runnable_MainActivity);
		else {
			isrun = false;
			try {
				runThread.join();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			handler.removeCallbacks(runnable_refreshlist);
		}

		if (myapp.Rpower.GetType() == PDATYPE.SCAN_ALPS_ANDROID_CUIUS2) {
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		Awl.ReleaseWakeLock();
		autostop = false;

		myapp.TagsMap.putAll(TagsMap);
		StopHandleUI();
		
	}
	String[] Coname=new String[]{"序号","EPC ID","次数","天线","协议","RSSI","频率","附加数据"};
 
	private void showlist()
	{
		 
		  Iterator<Entry<String, TAGINFO>> iesb;
		synchronized (this)
		{
		 Map<String, TAGINFO> TagsMap2=new LinkedHashMap<String, TAGINFO>();
		 TagsMap2.putAll(TagsMap);
		 iesb=TagsMap2.entrySet().iterator();
		}
            int j=1;
            
            ListMs.add(h);
 
            while(iesb.hasNext())
           { 
             TAGINFO bd=iesb.next().getValue();
             Map<String, String> m = new HashMap<String, String>();
             m.put(Coname[0], String.valueOf(j));
               j++;
             String epcstr=Reader.bytes_Hexstr(bd.EpcId);
             if(epcstr.length()<24)
            	epcstr=String.format("%-24s", epcstr);
             
             m.put(Coname[1], epcstr);
             String cs=m.get("次数");
             if(cs==null)
            	 cs="0";
             int isc=Integer.parseInt(cs)+bd.ReadCnt;
             
             m.put(Coname[2], String.valueOf(isc));
             m.put(Coname[3], String.valueOf(bd.AntennaID));
             m.put(Coname[4], "");
             m.put(Coname[5], String.valueOf(bd.RSSI));
             m.put(Coname[6], String.valueOf(bd.Frequency));
            
             if(bd.EmbededDatalen>0)
             {
            	 char[] out=new char[bd.EmbededDatalen*2];
            	 myapp.Mreader.Hex2Str(bd.EmbededData, bd.EmbededDatalen, out);
                m.put(Coname[7],String.valueOf(out));
             
             }
                 else
                	 m.put(Coname[7], "                 ");
             
         	ListMs.add(m);
           } 
        
		///*
        	Adapter = new MyAdapter(this, ListMs, R.layout.listitemview_inv,
    				Coname, new int[] { R.id.textView_readsort,
    						R.id.textView_readepc, R.id.textView_readcnt,
    						R.id.textView_readant, R.id.textView_readpro,
    						R.id.textView_readrssi, R.id.textView_readfre,
    						R.id.textView_reademd });
		 
		// layout为listView的布局文件，包括三个TextView，用来显示三个列名所对应的值
		// ColumnNames为数据库的表的列名 
		// 最后一个参数是int[]类型的，为view类型的id，用来显示ColumnNames列名所对应的值。view的类型为TextView
		listView.setAdapter(Adapter); 
		//*/
	}
	
	private Runnable runnable_MainActivity = new Runnable() {
		@Override
		public void run() {

			String[] tag = null;
			int[] tagcnt = new int[1];
			tagcnt[0] = 0;

			int streadt = 0, enreadt = 0;
			synchronized (this) {
				// Log.d("MYINFO", "ManActivity..1");
				READER_ERR er;
				streadt = (int) System.currentTimeMillis();
				if (myapp.nostop) {
					er = myapp.Mreader.AsyncGetTagCount(tagcnt);
				} else {
					er = myapp.Mreader.TagInventory_Raw(myapp.Rparams.uants,
							myapp.Rparams.uants.length,
							(short) myapp.Rparams.readtime, tagcnt);
				}
				//Log.d("MYINFO","read:" + er.toString() + " cnt:"+ String.valueOf(tagcnt[0]));

				if (er == READER_ERR.MT_OK_ERR) {
					if (tagcnt[0] > 0) {
						tv_once.setText(String.valueOf(tagcnt[0]));

						soundPool.play(1, 1, 1, 0, 0, 1);
						tag = new String[tagcnt[0]];
						for (int i = 0; i < tagcnt[0]; i++) {
							TAGINFO tfs = myapp.Mreader.new TAGINFO();
							if (myapp.Rpower.GetType() == PDATYPE.SCAN_ALPS_ANDROID_CUIUS2) {
								try {
									Thread.sleep(10);
								} catch (InterruptedException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
							if (myapp.nostop) 
								er=myapp.Mreader.AsyncGetNextTag(tfs);
							else
								er = myapp.Mreader.GetNextTag(tfs);
							
							//Log.d("MYINFO","get tag index:" + String.valueOf(i)+ " er:" + er.toString());
							if (er == READER_ERR.MT_HARDWARE_ALERT_ERR_BY_TOO_MANY_RESET) {

								tv_state.setText("error:"
										+ String.valueOf(er.value())
										+ er.toString());
								myapp.needreconnect = true;
								button_stop.performClick();
								autostop = true;
							}

							// Log.d("MYINFO","debug gettag:"+er.toString());
							// Log.d("MYINFO","debug tag:"+Reader.bytes_Hexstr(tfs.EpcId));

							if (er == READER_ERR.MT_OK_ERR) {
								tag[i] = Reader.bytes_Hexstr(tfs.EpcId);

								if (!TagsMap.containsKey(tag[i]))
									{
									   TagsMap.put(tag[i], tfs);
									   
									   //show
									   Map<String, String> m = new HashMap<String, String>();
										m.put(Coname[0], String.valueOf(TagsMap.size()));

										String epcstr = Reader
												.bytes_Hexstr(tfs.EpcId);
										if (epcstr.length() < 24)
											epcstr = String.format("%-24s", epcstr);

										m.put(Coname[1], epcstr);
										String cs = m.get("次数");
										if (cs == null)
											cs = "0";
										int isc = Integer.parseInt(cs) + tfs.ReadCnt;

										m.put(Coname[2], String.valueOf(isc));
										m.put(Coname[3],
												String.valueOf(tfs.AntennaID));
										m.put(Coname[4], "");
										m.put(Coname[5], String.valueOf(tfs.RSSI));
										m.put(Coname[6],
												String.valueOf(tfs.Frequency));

										if (tfs.EmbededDatalen > 0) {
											char[] out = new char[tfs.EmbededDatalen * 2];
											myapp.Mreader.Hex2Str(tfs.EmbededData,
													tfs.EmbededDatalen, out);
											m.put(Coname[7], String.valueOf(out));

										} else
											m.put(Coname[7], "                 ");

										ListMs.add(m);
									}
								else {
									TAGINFO tf = TagsMap.get(tag[i]);
									 
									String epcstr = tag[i];
									if (epcstr.length() < 24)
										epcstr = String.format("%-24s", epcstr);

									for (int k = 0; k < ListMs.size(); k++) {
										Map<String, String> m = (Map<String, String>) ListMs
												.get(k);
										if (m.get(Coname[1]).equals(epcstr)) {
											tf.ReadCnt += tfs.ReadCnt;
											tf.RSSI = tfs.RSSI;
											tf.Frequency = tfs.Frequency;

											m.put(Coname[2],
													String.valueOf(tf.ReadCnt));
											m.put(Coname[5],
													String.valueOf(tf.RSSI));
											m.put(Coname[6],
													String.valueOf(tf.Frequency));
											break;
										}
									}
								}

							} else
								break;
						}

						enreadt = (int) System.currentTimeMillis();
						tv_costt.setText("  "
								+ String.valueOf(enreadt - streadt));

					}

				} else {
					tv_state.setText("error:" + String.valueOf(er.value())
							+ " " + er.toString());
					if (er == READER_ERR.MT_HARDWARE_ALERT_ERR_BY_TOO_MANY_RESET) {
						tv_state.setText("error:" + String.valueOf(er.value())
								+ er.toString());
						myapp.needreconnect = true;
						button_stop.performClick();
						autostop = true;
					} else
						handler.postDelayed(this, myapp.Rparams.sleep);
					return;

				}
			}

			if (tag == null) {
				tag = new String[0];
			} else {

				if (!myapp.nostop) {
					Adapter.notifyDataSetChanged();
				} else {
					// if(System.currentTimeMillis() - Starttime>10000)
					{
						Log.d("MYINFO", "show");
						Adapter.notifyDataSetChanged();
						Starttime = (int) System.currentTimeMillis();
					}
				}
				// */
			}
			int cll = TagsMap.size();
			if (cll < 0)
				cll = 0;
			tv_tags.setText(String.valueOf(cll));
 
			handler.postDelayed(this, myapp.Rparams.sleep);
		}
	};
 	
 	private Runnable runnable_refreshlist = new Runnable( ) {
 		@Override
		public void run ( ) {
 			if(Adapter!=null)
 	 			Adapter.notifyDataSetChanged();
 			handler.postDelayed(this,myapp.refreshtime); 
 		}
 	};
 	
 	private Runnable runnable_alone = new Runnable( ) {
 		@Override
		public void run ( ) {
  
 			while(isrun){
 			   String[] tag = null;
 			
 			   int[] tagcnt=new int[1];
 			   
				tagcnt[0]=0;
				
				/*  清空过滤条件
				 myapp.Mreader.ParamSet(
						Mtr_Param.MTR_PARAM_TAG_FILTER,
						null);
						//*/
					//Log.d("MYINFO", "alone..1");
					READER_ERR er=myapp.Mreader.TagInventory_Raw
				    (myapp.Rparams.uants, myapp.Rparams.uants.length,
							(short) myapp.Rparams.readtime, tagcnt);
					Log.d("MYINFO","read:"+er.toString()+" cnt:"+String.valueOf(tagcnt[0]));
					
					if(er==READER_ERR.MT_OK_ERR)
					{
						  
						if(tagcnt[0]>0)
						{
							soundPool.play(1,1, 1, 0, 0, 1);
							tag=new String[tagcnt[0]];
							
							synchronized (this)
							{
						   for(int i=0;i<tagcnt[0];i++)
						  {
							
							TAGINFO tfs=myapp.Mreader.new TAGINFO();
							if(myapp.Rpower.GetType()==PDATYPE.SCAN_ALPS_ANDROID_CUIUS2)
							{
								try {
									Thread.sleep(10);
								} catch (InterruptedException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
							er=myapp.Mreader.GetNextTag(tfs);
							Log.d("MYINFO","get tag index:"+String.valueOf(i)+" er:"+er.toString());
							if(er==READER_ERR.MT_HARDWARE_ALERT_ERR_BY_TOO_MANY_RESET)
							{
								 Message msg2 = new Message(); 
					              msg2.what = 1;  
					              Bundle bundle2 = new Bundle(); 
					              bundle2.putString("Msg_error_1", "error:"+String.valueOf(er.value())+er.toString());
					              msg2.setData(bundle2);  
					              handler2.sendMessage(msg2);
								  isrun=false;
                                  myapp.needreconnect=true;
							}
						
						//	Log.d("MYINFO","debug gettag:"+er.toString());
						//	Log.d("MYINFO","debug tag:"+Reader.bytes_Hexstr(tfs.EpcId));

								if (er == READER_ERR.MT_OK_ERR) {
									tag[i] = Reader.bytes_Hexstr(tfs.EpcId);

									// 过滤读tid----------------
									/*try {
										byte[] rdata = new byte[12];

										byte[] rpaswd = new byte[4];
										TagFilter_ST g2tf = myapp.Mreader.new TagFilter_ST();
										g2tf.fdata = tfs.EpcId;
										g2tf.flen = tfs.EpcId.length * 8;

										g2tf.isInvert = 0;

										g2tf.bank = 1;

										g2tf.startaddr = 32;

										er = myapp.Mreader.ParamSet(
												Mtr_Param.MTR_PARAM_TAG_FILTER,
												g2tf);
										er = myapp.Mreader.GetTagData(
												tfs.AntennaID, (char) 2, 0, 6,
												rdata, rpaswd, (short) 1000);
										if(er==READER_ERR.MT_OK_ERR)
										{String val = "";
										char[] out = null;

										out = new char[rdata.length*2];
										myapp.Mreader.Hex2Str(rdata,
												rdata.length, out);
										val = String.valueOf(out).trim();
										
										Log.d("MYINFO", "er:"+er.toString()+" tid:"+val);
										// 清除过滤
										g2tf = null;
										er = myapp.Mreader.ParamSet(
												Mtr_Param.MTR_PARAM_TAG_FILTER,
												g2tf);
										}
									} catch (Exception ex) {

									}
								 		*/
									
								 if(!TagsMap.containsKey(tag[i]))
				       		       TagsMap.put(tag[i],tfs);
							    else
								{ 
								  TAGINFO tf=TagsMap.get(tag[i]);
								  tf.ReadCnt+=tfs.ReadCnt;
								  tf.RSSI=tfs.RSSI;
								  tf.Frequency=tfs.Frequency;
								}
							 
							}
							else
								break;
						 }
						}
						
						}
						
					}
					else
					{
						//Log.d("MYINFO", "alone..Msg_error_2");
		 				 try {
							Thread.sleep(myapp.Rparams.sleep);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
		 				  Message msg = new Message(); 
		 				  
		 				  Bundle bundle = new Bundle(); 
			              bundle.putString("Msg_error_2", "error:"+String.valueOf(er.value())+" "+er.toString());
			              msg.setData(bundle); 
			              
			              
			              if(er==READER_ERR.MT_HARDWARE_ALERT_ERR_BY_TOO_MANY_RESET)
							 { 
								myapp.needreconnect=true;
								isrun=false;
								msg.what=1;
							 }
			              else
			              {
			            	  msg.what = 2; 
			              }
			              handler2.sendMessage(msg);
			              continue;
					}
				 
 			     if(tag==null)
 			    {
 			       tag=new String[0];
 			    }
 			  
 			      if(tagcnt[0]>0)
 			      { Message msg = new Message(); 
 			      Bundle bundle = new Bundle(); 
 			      msg.what = 0;  
 			      bundle.putString("Msg_cnt", (String.valueOf(tagcnt[0])));
 			      synchronized (this)
					{
 			    	 bundle.putString("Msg_all", (String.valueOf(TagsMap.size())));
					}
	              msg.setData(bundle);  
	              handler2.sendMessage(msg);
 			      }
 				try {
					Thread.sleep(myapp.Rparams.sleep);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
 				//Log.d("MYINFO", "alone..2");
 			}
 		}
 	};
 	
 
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if(!button_read.isEnabled())
		{
			 Toast.makeText(MainActivityTwo.this, "请先停止工作",
						Toast.LENGTH_SHORT).show();  
		}
		else{
		
		if (id == R.id.action_system) {
			
			Intent intent = new Intent(MainActivityTwo.this, SubSystemActivity.class);
			startActivityForResult(intent, 0); 
			return true;
		}}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_main, container,
					false);
			return rootView;
		}
	}
	


	private void ReadHandleUI()
	{
		 this.button_read.setEnabled(false);
	        this.button_stop.setEnabled(true);
	        TabWidget tw=myapp.tabHost.getTabWidget();
	        if(RULE_NOSELPT)
	        {
	        	 tw.getChildAt(1).setEnabled(false);
				 tw.getChildAt(2).setEnabled(false);
	        }
	        else{
			 tw.getChildAt(0).setEnabled(false);
			 tw.getChildAt(2).setEnabled(false);
			 tw.getChildAt(3).setEnabled(false);
	        }
	}
	private void StopHandleUI()
	{
		button_read.setEnabled(true);
		button_stop.setEnabled(false);
		 TabWidget tw=myapp.tabHost.getTabWidget();
		 if(RULE_NOSELPT)
		 {
			 tw.getChildAt(1).setEnabled(true);
			 tw.getChildAt(2).setEnabled(true);
		 }
		 else
		 {tw.getChildAt(0).setEnabled(true);
		 tw.getChildAt(2).setEnabled(true);
		 tw.getChildAt(3).setEnabled(true);
		 }
	}
	
	//for CZ8800
	public void setScanner(boolean enable) {
        int onOff = 0;
        if (enable)
            onOff = 1;
        /*Settings.System.putInt(mContext.getContentResolver(),
                "SCANNER_POWER_ON", onOff);
        Intent intent = new Intent(
                "com.android.server.scannerservice.settingchange", null);
        mContext.sendBroadcast(intent, null);*/
        
        Intent intent = new Intent( "com.android.server.scannerservice.onoff"); 
        if (enable) { 
        intent.putExtra("scanneronoff", 1); 
        } else { 

        intent.putExtra("scanneronoff", 0); 
        } 
        sendBroadcast(intent);
       // mContext.sendBroadcast(intent); 
    }
	 public boolean isScannerEnable() {
	        int enable = Settings.System.getInt(getContentResolver(),
	                "SCANNER_POWER_ON", 1);
	        if (enable == 1)
	            return true;
	        else
	            return false;
	    }

	// 一维扫描头开关状态的判定：
	    public boolean isUartScannerEnable() {
	        int enable = Settings.System.getInt(getContentResolver(),
	                "UARTSCANNER_POWER_ON", 1);
	        if (enable == 1)
	            return true;
	        else
	            return false;
	    }

	//设置一维扫描引擎的开或者关：
	    public void setUartScanner(boolean enable) {
	        int onOff = 0;
	        if (enable)
	            onOff = 1;
	       
	        Intent intent = new Intent( "com.android.server.uartscannerservice.onoff");
	        if (enable) {
	        intent.putExtra("scanneronoff", 1);
	        } else {

	        intent.putExtra("scanneronoff", 0);
	        }
	        sendBroadcast(intent);
	    }

	@Override
	public void onResume() {
		//if (myapp.Rpower != null && myapp.Rpower.GetType() == PDATYPE.CZ880) {
		
		/*
		Log.e("scannerCheck", "2D isScannerEnable()++++");
			if (isScannerEnable()) {
				Log.e("scannerCheck", "2D isScannerEnable()-----");
				D2 = true;
				// 关闭二维
				Log.e("scannerCheck", "2D setScanner(false);+++++");
				setScanner(false);
				Log.e("scannerCheck", "2D setScanner(false);-----");
			} else
				{
				   D2 = false;
				   Log.e("scannerCheck", "2D :false-----");
				}
			Log.e("scannerCheck", "1D isUartScannerEnable()++++");
			if (isUartScannerEnable()) {
				Log.e("scannerCheck", "1D isUartScannerEnable()----");
				D1 = true;
				// 关闭一维
				Log.e("scannerCheck", "1D setUartScanner(false);+++++");
				setUartScanner(false);
				Log.e("scannerCheck", "1D setUartScanner(false);-----");
			} else
				D1 = false;
	//	}
		/*
		 * if(autostop) button_read.performClick();
		 */
		super.onResume();

	}
	
	@Override
	public void onPause(){
		//if(myapp.Rpower.GetType()==PDATYPE.CZ880)
		//{
			/*
			if(D2){
				   Log.e("scannerCheck","2D setScanner(true);+++++");
				   
				   setScanner(true);
				   Log.e("scannerCheck","2D setScanner(true);-----");
				  }
				  
				  if(D1){
				   Log.e("scannerCheck","1D setScanner(true);+++++");
 
				   setUartScanner(true);
				   Log.e("scannerCheck","1D setScanner(true);-----");
				  }
				  
				  button_stop.performClick();
				   myapp.needreconnect=true;
				   myapp.Rpower.PowerDown();
				   */
		//}
		super.onPause();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){   
	        if((System.currentTimeMillis()-myapp.exittime) > 2000){  
	            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();                                
	            myapp.exittime = System.currentTimeMillis();   
	        } else {
	        	if(handler!=null)
	        	handler.removeCallbacks(runnable_MainActivity); 
	        	if(myapp.Mreader!=null)
	 				myapp.Mreader.CloseReader();
	 				
	 			myapp.Rpower.PowerDown();
	            finish();
	           // System.exit(0);
	        }
	        return true;   
	    }
	    return super.onKeyDown(keyCode, event);
	}
	 
	
	private void ConnectHandleUI()
	{
		try
		{
			READER_ERR er;
			myapp.Rparams=myapp.spf.ReadReaderParams();
			
			 if(myapp.Rparams.invpro.size()<1)
				 myapp.Rparams.invpro.add("GEN2");
		   
		    	 List<SL_TagProtocol> ltp=new ArrayList<SL_TagProtocol>();
				   for(int i=0;i<myapp.Rparams.invpro.size();i++)
				   {  if(myapp.Rparams.invpro.get(i).equals("GEN2"))
				    	{ ltp.add(SL_TagProtocol.SL_TAG_PROTOCOL_GEN2);
				    	 
				    	}
				   else if(myapp.Rparams.invpro.get(i).equals("6B"))
				    	{
				    	  ltp.add(SL_TagProtocol.SL_TAG_PROTOCOL_ISO180006B);
				    	 
				    	}
				   else if(myapp.Rparams.invpro.get(i).equals("IPX64"))
				    	{
				    	   ltp.add(SL_TagProtocol.SL_TAG_PROTOCOL_IPX64);
				    	   
				    	}
				   else if(myapp.Rparams.invpro.get(i).equals("IPX256"))
				    	{
				    	  ltp.add(SL_TagProtocol.SL_TAG_PROTOCOL_IPX256);
				    	  
				    	}
				   }
				     
					Inv_Potls_ST ipst=myapp.Mreader.new Inv_Potls_ST();
					ipst.potlcnt=ltp.size();
					ipst.potls=new Inv_Potl[ipst.potlcnt];
					SL_TagProtocol[] stp=ltp.toArray(new SL_TagProtocol[ipst.potlcnt]);
					for(int i=0;i<ipst.potlcnt;i++)
					{
						Inv_Potl ipl=myapp.Mreader.new Inv_Potl();
						ipl.weight=30;
						ipl.potl=stp[i];
						ipst.potls[0]=ipl;
					}
					
				  er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_TAG_INVPOTL, ipst);
			      Log.d("MYINFO", "Connected set pro:"+er.toString());
	 
			 er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_READER_IS_CHK_ANT,
					 new int[]{myapp.Rparams.checkant});
			 Log.d("MYINFO", "Connected set checkant:"+er.toString());
			 
				
			 AntPowerConf apcf=myapp.Mreader.new AntPowerConf();
				apcf.antcnt=myapp.antportc;
				for(int i=0;i<apcf.antcnt;i++)
				{
					AntPower jaap=myapp.Mreader.new AntPower();
					jaap.antid=i+1;
					jaap.readPower =(short)myapp.Rparams.rpow[i];
					jaap.writePower=(short)myapp.Rparams.wpow[i];
					apcf.Powers[i]=jaap; 
				}
				
			myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_RF_ANTPOWER, apcf);
			 
			Region_Conf rre;
			 switch(myapp.Rparams.region)
			 {
			 case 0:
				 rre =Region_Conf.RG_PRC;
				 break;
			 case 1:
				 rre = Region_Conf.RG_NA;
				 break;
			 case 2:
				 rre=Region_Conf.RG_NONE;
				 break;
			 case 3:
				 rre=Region_Conf.RG_KR;
				 break;
			 case 4:
				 rre=Region_Conf.RG_EU;
				 break;
			 case 5:
			 case 6:
			 case 7:
			 case 8:
			 default:
				 rre=Region_Conf.RG_NONE;
				 break;
			 }
			 if(rre!=Region_Conf.RG_NONE)
			 {
				 er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_FREQUENCY_REGION,rre);
			 }
  
			if(myapp.Rparams.frelen>0)
			{
				 
					HoptableData_ST hdst=myapp.Mreader.new HoptableData_ST();
					hdst.lenhtb=myapp.Rparams.frelen;
					hdst.htb=myapp.Rparams.frecys;
					  er=myapp.Mreader.ParamSet
							(Mtr_Param.MTR_PARAM_FREQUENCY_HOPTABLE,hdst);
			}
			 
			er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_POTL_GEN2_SESSION,
							new int[]{myapp.Rparams.session});
			er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_POTL_GEN2_Q,
					new int[]{myapp.Rparams.qv});
			er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_POTL_GEN2_WRITEMODE,
					new int[]{myapp.Rparams.wmode});
			er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_POTL_GEN2_MAXEPCLEN,
					new int[]{myapp.Rparams.maxlen});
			er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_POTL_GEN2_TARGET,
					new int[]{myapp.Rparams.target});
			 
			if(myapp.Rparams.filenable==1)
			{
				 TagFilter_ST tfst=myapp.Mreader.new TagFilter_ST();
				 tfst.bank=myapp.Rparams.filbank;
				 tfst.fdata=new byte[myapp.Rparams.fildata.length()/2];
				 myapp.Mreader.Str2Hex(myapp.Rparams.fildata,
						 myapp.Rparams.fildata.length(), tfst.fdata);
				 tfst.flen=tfst.fdata.length*8;
				 tfst.startaddr=myapp.Rparams.filadr;
				 tfst.isInvert=myapp.Rparams.filisinver;
		       
				 myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_TAG_FILTER, tfst);
			}
		 
			if(myapp.Rparams.emdenable==1)
			{
				EmbededData_ST edst = myapp.Mreader.new EmbededData_ST();
				 
				edst.accesspwd=null;
				edst.bank=myapp.Rparams.emdbank;
				edst.startaddr=myapp.Rparams.emdadr;
				edst.bytecnt=myapp.Rparams.emdbytec;
				edst.accesspwd=null;
			 
				er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_TAG_EMBEDEDDATA,
						edst);
			}
			 
			er=myapp.Mreader.ParamSet
					(Mtr_Param.MTR_PARAM_TAGDATA_UNIQUEBYEMDDATA,
							new int[]{myapp.Rparams.adataq});
			er=myapp.Mreader.ParamSet
					(Mtr_Param.MTR_PARAM_TAGDATA_RECORDHIGHESTRSSI, 
							new int[]{myapp.Rparams.rhssi});
			er=myapp.Mreader.ParamSet
					(Mtr_Param.MTR_PARAM_TAG_SEARCH_MODE, 
							new int[]{myapp.Rparams.invw});
			
			TextView tv_module=(TextView)findViewById(R.id.textView_module);
			TextView tv_tempurte=(TextView)findViewById(R.id.textView_tempture);
			HardwareDetails val=myapp.Mreader.new HardwareDetails();
			er=myapp.Mreader.GetHardwareDetails(val);
			if(er==READER_ERR.MT_OK_ERR)
			{
				tv_module.setText(val.module.toString());
			}
		 
		}catch(Exception ex)
		{
			Log.d("MYINFO", ex.getMessage()+ex.toString()+ex.getStackTrace());
		}
	        
	}
	public class KeyReceiver extends BroadcastReceiver {

		private String TAG = "KeyReceiver" ;
		@Override
		public void onReceive(Context context, Intent intent) {
			int keyCode = intent.getIntExtra("keyCode", 0) ;
			boolean keyDown = intent.getBooleanExtra("keydown", false) ;
//			Log.e("down", ""+keyDown);
			if(keyDown){
				switch (keyCode) {
					case KeyEvent.KEYCODE_F1:
						if (button_read.isEnabled()) {
							start_read();
						}else
						if (button_stop.isEnabled()) {
							stop_read();
						}
						break;
					case KeyEvent.KEYCODE_F2:
						if (button_read.isEnabled()) {
							start_read();
						}else
						if (button_stop.isEnabled()) {
							stop_read();
						}
						break;
					case KeyEvent.KEYCODE_F3:
						if (button_read.isEnabled()) {
							start_read();
						}else
						if (button_stop.isEnabled()) {
							stop_read();
						}
						break;
					case KeyEvent.KEYCODE_F5:
						if (button_read.isEnabled()) {
							start_read();
						}else
						if (button_stop.isEnabled()) {
							stop_read();
						}
						break;
					case KeyEvent.KEYCODE_F4:
						if (button_read.isEnabled()) {
							start_read();
						}else
						if (button_stop.isEnabled()) {
							stop_read();
						}
						break;
				}
			}else {
				Log.e("up", ""+keyCode);
			}

		}

	}
}
